<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入医生名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- 只有管理员和医院负责人可以看到排班按钮 -->
        <el-button type="primary" @click="arrangeSchedule" v-if="hasPermission(['admin', 'director'])"
                   v-hasPermi="['dcp:scheduling:add']">排班</el-button>
      </el-col>
      <el-button type="primary" @click="prevWeek">上一周</el-button>
      <el-button type="primary" @click="nextWeek">下一周</el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 排班表格 -->
    <div class="schedule-table">
      <el-table :data="timeSlots" border style="width: 100%">
        <el-table-column prop="timeSlot" label="时间段" width="120"></el-table-column>
        <el-table-column v-for="(day, index) in weekDays" :key="index" :label="day.label" :prop="day.value">
          <template slot-scope="scope">
            <div v-for="(doctor, idx) in getDoctorsForTimeSlot(scope.row.timeSlot, day.value)" :key="idx"
                 class="doctor-item">
              <span>{{ doctor.userName }}</span>
              <!-- <span>{{ doctor. }}</span> -->
              <!-- 添加操作按钮，仅管理员和医院负责人可见 -->
              <div class="doctor-actions" v-if="hasPermission(['admin', 'director'])">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(doctor)"
                           v-hasPermi="['dcp:scheduling:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(doctor)"
                           v-hasPermi="['dcp:scheduling:remove']">删除</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/修改排班对话框 - 只有管理员和医院负责人可以操作 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="医生名称" prop="userName">
          <el-select v-model="form.userId" placeholder="请选择医生" @change="handleDoctorChange">
            <el-option
              v-for="item in doctorOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="排班医生"> <el-select v-model="form.userName" :disabled="!!form.id" style="width: 100%"
                                               @change="handleDoctorChange">
          <el-option v-for="doctor in doctors" :key="doctor.userId" :label="doctor.nickName"
                     :value="doctor.nickName" />
        </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="工作内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入工作内容" />
        </el-form-item>
        <el-form-item label="排班日期" prop="schedulingDate">
          <el-date-picker v-model="form.schedulingDate" type="date" placeholder="选择日期"
                          value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="开始节次" prop="start">
          <el-select v-model="form.start" placeholder="请选择开始节次">
            <el-option label="上午8-9" value="1"></el-option>
            <el-option label="上午10-12" value="2"></el-option>
            <el-option label="下午1-2" value="3"></el-option>
            <el-option label="下午4-6" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结束节次" prop="end">
          <el-select v-model="form.end" placeholder="请选择结束节次">
            <el-option label="上午8-9" value="1"></el-option>
            <el-option label="上午10-12" value="2"></el-option>
            <el-option label="下午1-2" value="3"></el-option>
            <el-option label="下午4-6" value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScheduling, getScheduling, delScheduling, addScheduling, updateScheduling } from "@/api/dcp/scheduling";
import { parseTime } from '@/utils/ruoyi';
import { listDoctor } from "@/api/system/user";
import { listUser } from '../../../api/system/user'
export default {
  name: "DoctorScheduling",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排班记录表格数据
      schedulingList: [],
      // 医生排班数据（用于表格显示）
      doctorSchedules: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前周的开始日期
      currentWeekStart: new Date(),
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        title: null,
        content: null,
        start: null,
        end: null,
        schedulingDate: null,
      },
      // 表单参数
      form: {

      },
      doctors: [],
      // 表单校验
      rules: {},
      // 时间段
      timeSlots: [
        { timeSlot: "上午8-9" },
        { timeSlot: "上午10-12" },
        { timeSlot: "下午1-2" },
        { timeSlot: "下午4-6" }
      ],

      // 周天数据
      weekDays: [], // 用于存储处理后的排班数据
      // 医生选项列表
      doctorOptions: [],
    };
  },
  created() {
    // 获取用户信息
    this.getUserInfo();
    // 确保在页面创建时调用获取数据的方法
    this.getList();
    this.initWeekDays();
    // 获取医生信息
    this.getDoctorList();
  },
  methods: {
    // 获取用户信息
    // 获取用户信息
    // 获取用户信息
    getUserInfo() {

      // // 获取用户角色
      this.userRoles = this.$store.getters && this.$store.getters.roles || [];

      // 获取用户对象
      const user = this.$store.state;

      // 从用户对象中获取userId和deptId
      this.userId = user && user.user.id;
      this.deptId = user && user.deptId;
      const a = this.$store.getters;
      // 添加调试信息
      // console.log('当前用户角色:', this.userRoles);
      // console.log('当前用户对象:', user);
      // console.log('当前用户对象111:', a);

      // console.log('当前用户ID:', this.userId);
      // console.log('当前部门ID:', this.deptId);
    },
    // 获取医生列表
    getDoctorList() {
      listUser().then(response => {
        this.doctors = response.rows;
      });
    },
    handleDoctorChange(selectedName) {
      const doctor = this.doctors.find(d => d.nickName === selectedName);
      if (doctor) this.form.userId = doctor.userId;
    },
    // 检查用户是否有指定角色权限
    hasPermission(roles) {
      const userRoles = this.$store.getters && this.$store.getters.roles;
      return roles.some(role => userRoles.includes(role));
    },

    // 初始化周天数据
    initWeekDays() {
      const weekStart = this.getWeekStartDate(this.currentWeekStart);
      this.weekDays = [];

      for (let i = 0; i < 5; i++) {
        const date = new Date(weekStart);
        date.setDate(date.getDate() + i);
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const weekDay = ["星期一", "星期二", "星期三", "星期四", "星期五"][i];

        this.weekDays.push({
          label: `${weekDay}\n${month}.${day}`,
          value: `day${i + 1}`,
          date: parseTime(date, '{y}-{m}-{d}')
        });
      }
    },

    // 获取周一日期
    getWeekStartDate(date) {
      const day = date.getDay() || 7;
      const diff = day === 1 ? 0 : 1 - day;
      const monday = new Date(date);
      monday.setDate(date.getDate() + diff);
      return monday;
    },

    // 上一周
    prevWeek() {
      const date = new Date(this.currentWeekStart);
      date.setDate(date.getDate() - 7);
      this.currentWeekStart = date;
      this.initWeekDays();
      this.getList();
    },

    // 下一周
    nextWeek() {
      const date = new Date(this.currentWeekStart);
      date.setDate(date.getDate() + 7);
      this.currentWeekStart = date;
      this.initWeekDays();
      this.getList();
    },

    /** 查询排班记录列表 */
    getList() {

      this.loading = true;

      // 获取当前周的开始和结束日期
      const weekStart = this.getWeekStartDate(this.currentWeekStart);
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);

      const query = {
        ...this.queryParams,
        beginSchedulingDate: parseTime(weekStart, '{y}-{m}-{d}'),
        endSchedulingDate: parseTime(weekEnd, '{y}-{m}-{d}')
      };

      // 添加调试信息
      // console.log('查询前的参数:', query);
      // console.log('当前用户角色:', this.userRoles);

      // 根据角色设置查询条件
      if (this.userRoles.includes('doctor') && !this.userRoles.includes('admin') && !this.userRoles.includes('director')) {
        // 医生只能查看自己的排班
        query.userId = this.userId;
        // console.log('医生角色，设置查询条件 userId:', this.userId);
      } else if (this.userRoles.some(role => role.includes('hospital') || role.includes('dept') || role.includes('manager')) && !this.userRoles.includes('admin')) {
        // 医院负责人只能查看本部门的排班
        // 使用更宽松的角色匹配，捕获可能的医院管理者角色
        query.deptId = this.deptId;
        // console.log('医院负责人角色，设置查询条件 deptId:', this.deptId);
      }
      // 管理员可以查看所有排班，不需要额外条件

      // console.log('最终查询参数:', query);

      listScheduling(query).then(response => {

        // console.log('查询结果:', response);
        this.schedulingList = response.rows;
        this.total = response.total;
        this.loading = false;
        // console.log('获取到的排班数据:', this.schedulingList);
      }).catch(error => {
        console.error('查询排班出错:', error);
        this.loading = false;
      });
    },

    // 处理排班数据以适应表格显示
    processSchedulingData() {
      // 清空现有数据
      this.doctorSchedules = [];

      // 遍历获取的排班数据，重新格式化为表格所需格式
      this.schedulingList.forEach(item => {
        // 确保日期格式正确
        const scheduleDate = item.schedulingDate;
        const dayOfWeek = this.getDayOfWeek(scheduleDate);

        // 将数据添加到doctorSchedules数组
        this.doctorSchedules.push({
          timeSlot: item.start, // 使用开始节次作为时间段
          day: dayOfWeek,
          userName: item.userName,
          title: item.title,
          content: item.content
        });
      });

      // console.log('处理后的排班数据:', this.doctorSchedules);
    },

    // 获取日期对应的星期几
    getDayOfWeek(dateString) {
      const date = new Date(dateString);
      // 返回0-6，对应周日到周六
      return date.getDay();
    },

    // 获取指定时间段和日期的医生列表
    getDoctorsForTimeSlot(timeSlot, dayValue) {
      // 将时间段文本转换为对应的数值
      let timeSlotValue;
      switch (timeSlot) {
        case "上午8-9": timeSlotValue = 1; break;
        case "上午10-12": timeSlotValue = 2; break;
        case "下午1-2": timeSlotValue = 3; break;
        case "下午4-6": timeSlotValue = 4; break;
        default: timeSlotValue = null;
      }

      // 获取当前日期
      const dayIndex = parseInt(dayValue.replace('day', '')) - 1;
      if (dayIndex < 0 || dayIndex >= this.weekDays.length) {
        return [];
      }

      const currentDate = this.weekDays[dayIndex].date;

      // 添加调试信息
      // console.log(`查找时间段: ${timeSlot}(${timeSlotValue}), 日期: ${currentDate}`);

      // 筛选符合条件的医生排班
      const doctors = this.schedulingList.filter(item => {
        // 检查日期是否匹配
        const dateMatch = item.schedulingDate === currentDate;

        // 检查时间段是否在排班的开始和结束之间
        const startTime = parseInt(item.start);
        const endTime = parseInt(item.end);
        const timeMatch = timeSlotValue >= startTime && timeSlotValue <= endTime;

        // 添加调试信息
        // console.log(`比较: 排班项=${JSON.stringify(item)}, 日期匹配=${dateMatch}, 时间段匹配=${timeMatch}`);

        return dateMatch && timeMatch;
      });

      // console.log(`找到的医生数量: ${doctors.length}`);
      return doctors;
    },
    // 排班操作
    arrangeSchedule() {
      this.reset();
      this.open = true;
      this.title = "添加排班";
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        schedulingId: null,
        userId: null,
        userName: null,
        title: null,
        content: null,
        start: null,
        end: null,
        schedulingDate: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.schedulingId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加排班记录";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const schedulingId = row.schedulingId;
      this.reset();
      this.open = true;
      this.title = "修改排班信息";
      getScheduling(schedulingId).then(response => {
        this.form = response.data;
        // 确保日期格式正确
        if (this.form.schedulingDate) {
          this.form.schedulingDate = parseTime(this.form.schedulingDate, '{y}-{m}-{d}');
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const schedulingId = row.schedulingId;
      this.$modal.confirm('是否确认删除该排班信息？').then(function () {
        return delScheduling(schedulingId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    calculateScheduleData() {
      // 清除可能的缓存数据
      this.schedulingList = [...this.schedulingList]; // 创建新数组触发响应式更新

      // 如果您使用了过滤方法，请确保过滤条件不会排除新添加的数据
      if (this.getDoctorsForTimeSlot) {
        // 强制重新计算排班表格数据
        this.$forceUpdate();
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果是医院负责人，设置部门ID
          if (this.userRoles.includes('director') && !this.userRoles.includes('admin')) {
            this.form.deptId = this.deptId;
          }

          if (this.form.schedulingId != null) {
            updateScheduling(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('修改排班出错:', error);
              this.$modal.msgError("修改失败");
            });
          } else {
            addScheduling(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('新增排班出错:', error);
              this.$modal.msgError("新增失败");
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.schedule-table {
  margin-top: 20px;
}

.doctor-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px dashed #eee;
}

.doctor-item:last-child {
  border-bottom: none;
}

.doctor-actions {
  display: flex;
}
</style>

<style scoped>
.schedule-table {
  margin-top: 20px;
}
</style>
